package heman.server.controllers;

import heman.server.entities.Player;
import heman.server.entities.PlayerManager;
import heman.server.entities.Table;
import heman.server.entities.TableManager;
import heman.server.entities.TableType;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.server.interfaces.IProcessServerMessage;

/**
 * Invite controller handles INVITE message.
 * <xs:element name="invite">
 * 	<xs:complexType>
 * 		<xs:attribute name="table" type="table-id" use="required" /> 
 * 		<xs:attribute name="player" type="valid-player-id" use="required" /> 
 * 	</xs:complexType>
 * </xs:element>
 *
 * @author Yanyi Zhang
 *
 */

public class InviteController implements IProcessServerMessage {
	public boolean process(Communicator com, Message m){
		String originator = m.getOriginator();
		NamedNodeMap map=m.contents().getAttributes();
		String tableID=map.
        		getNamedItem("table").getNodeValue();
		Table TargetTable=TableManager.getInstance().getTable(tableID);
		if(!TargetTable.getType().equals(TableType.BY_INVITATION))
			return false;//its not a by_invitation table
		String playerID=map.getNamedItem("player").getNodeValue();
		Player TargetPlayer=PlayerManager.getInstance().getPlayer(playerID);
		if(TargetTable.invitePlayer(TargetPlayer)) {
			StringBuilder sb = new StringBuilder(Message.requestHeader());
			sb.append("<confirm table=\"");
			sb.append(tableID);
			sb.append("\" player=\"");
			sb.append(originator);
			sb.append("\"/></request>");
			Document d = Message.construct(sb.toString());
		    Message r = new Message (d);
		    r.setOriginator(originator);
		    r.setRecipient(playerID);
		    return com.distribute(r);
		}
		return false;
	}
}
